using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.Traceabilitys.DeepProcessings;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.Traceabilitys.DeepProcessings
{
    /// <summary>
    /// 获取深加工企业信息命令处理
    /// </summary>
    public class GetDeepProcessingCorporateCommandHandlter : IRequestHandler<GetDeepProcessingCorporateCommand, ApiResult<List<DeepProcessingCorporateModel>>>
    {
        /// <summary>
        /// 深加工企业信息仓储
        /// </summary>
        private readonly IBaseRepository<DeepProcessingCorporateModel> deepProcessingCorporateRep;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="deepProcessingCorporateRep">深加工企业信息仓储</param>
        public GetDeepProcessingCorporateCommandHandlter(IBaseRepository<DeepProcessingCorporateModel> deepProcessingCorporateRep)
        {
            this.deepProcessingCorporateRep = deepProcessingCorporateRep;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiResult<List<DeepProcessingCorporateModel>>> Handle(GetDeepProcessingCorporateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据溯源编号获取深加工企业信息，并按时间倒序排序
                var corporateList = await deepProcessingCorporateRep.GetAll()
                    .Where(p => p.ProductId == request.ProductId)
                    .OrderByDescending(p => p.CreaTime)
                    .ToListAsync(cancellationToken);

                return new ApiResult<List<DeepProcessingCorporateModel>>
                {
                    code = ResultEnumCode.Ok,
                    data = corporateList,
                    message = corporateList.Any() ? "获取成功" : "未找到相关深加工企业信息"
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<DeepProcessingCorporateModel>>
                {
                    code = ResultEnumCode.fails,
                    data = null,
                    message = $"获取深加工企业信息失败: {ex.Message}"
                };
            }
        }
    }
} 